from django.shortcuts import render, HttpResponse, redirect
from django.views.generic import View
from django.http.response import JsonResponse
from django.contrib.auth import authenticate, login, logout # 导入django内置认证方法
from .models import User
from .utils.captcha_image import generate_captcha_image # 导入生成验证码工具方法
# Create your views here.
from django.http import HttpResponse
from django.conf import settings
from utils.mixin import LoginRequiredMixin

# 与前端约束的返回
result_fail = settings.RES_FAIL
result_success = settings.RES_SUCCESS

# 首页视图
class Index(LoginRequiredMixin, View):

    def get(self, request):
        return HttpResponse("<h1>apps user's index!</h1>")

# 验证码视图类
# /user/get_auth_img
class GetAuthImg(View):
    """获取验证码视图类"""

    def get(self, request):

        # 生成验证码图片： 验证码值、 验证码图片
        image_code, image_bytes = generate_captcha_image()

        # 存入session，用于做进一步验证
        request.session['authcode'] = image_code

        # 将内存中的图片数据返回给客户端，MIME类型为图片png
        return HttpResponse(image_bytes, 'image/png')

# 用户登录视图类
# /user/login
class Login(View):

    def get(self, request):
        # get请求返回登录页面

        # 判断用户是否已登陆
        # 获取当前的用户
        user = request.user  # 获取当前的用户

        # 判断用户是否已登陆
        if user.is_authenticated:  # 用户已登陆, 则跳至首页
            return redirect('user:index')

        # 用户未登陆，则进入登陆页
        return render(request, "user/login.html")

    def post(self, request):
        data = request.POST
        # 获取用户登录信息
        authcode = data.get("authcode")
        username = data.get("username")
        password = data.get("password")

        print(f'authcode = {authcode}, \n'
              f'username = {username}, \n'
              f'password = {password}')

        # 验证码不正确
        if request.session.get("authcode").upper() != authcode.upper():
            return JsonResponse({"status": "1", "message": "Verification code error"})
        else:
            # 使用django的auth模块进行用户名密码验证
            user = authenticate(username=username, password=password)
            if user:
                # 登录成功
                # 将用户名存入session中
                request.session["user"] = username
                login(request, user)  # 将用户信息添加到session中
                # return JsonResponse({"status": "2", "message": "Loggin sucessful"})
                return redirect('user:index')
            else:
                # 账号或密码错误
                return JsonResponse({"status": "3", "message": "Wrong account or password"})


# 注册视图类
# /user/register
class Register(View):
    """注册视图类"""

    def get(self, request):
        # 注册页面的生成我们并没有用form，因为我们使用的别人的模板样式
        return render(request, "user/register.html")

    def post(self, request):
        # post请求提交注册数据


        # 接受参数
        username = request.POST.get("username")
        email = request.POST.get("email")
        phone = request.POST.get("phone")
        password = request.POST.get("password")
        r_password = request.POST.get("r_password")

        # 校验参数
        # 1.使用all()所有参数是否都接收到
        if not all([username, email, phone,password,r_password]):
            # 说明数据不完整，返回注册页面
            return render(request, 'user/register.html')

        # 2.校验用户名是否重复
        try:
            user = User.objects.get(username=username)  # 当用户名存在，则返回user对象
        except User.DoesNotExist:
            user = None  # 当用户名不存在，则会报DoseNotExist的异常，此时设置user = None

        if user:  # 如果user为对象，则用户名存在，直接返回错误信息
            return render(request, 'user/register.html')

        # 业务处理：用户注册
        # 调用django的用户认证系统进行用户新增
        user = User.objects.create_user(username=username, password=password, email=email, phone=phone)
        user.is_active = 1 # 注册用户
        user.save()

        # 注册成功，返回登陆页
        return redirect('user:login')

        # # 设置返回信息
        # result_success['message'] = {
        #     "username": username,
        #     "email": email,
        #     "phone": phone,
        #     "password": password,
        #     "r_password": r_password,
        # }
        # return JsonResponse(result_success)

